import React, { useState, useEffect } from 'react'
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  message,
  Statistic,
  Row,
  Col,
  Popconfirm,
  Tooltip,
  Alert,
  Tabs
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  HistoryOutlined,
  ReloadOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined
} from '@ant-design/icons'
import { useQuery, useMutation, useQueryClient } from 'react-query'
import { jobApi, jobUtils, Job, JobCreateRequest, JobUpdateRequest } from '../services/job'
import type { ColumnsType } from 'antd/es/table'

const { TextArea } = Input
const { Option } = Select
const { TabPane } = Tabs

const JobManagement: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingJob, setEditingJob] = useState<Job | null>(null)
  const [form] = Form.useForm()
  const [searchText, setSearchText] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('')
  const [debugInfo, setDebugInfo] = useState<{
    hasToken: boolean
    tokenPreview: string
    apiBaseUrl: string
  }>({ hasToken: false, tokenPreview: '', apiBaseUrl: '' })
  const [testResult, setTestResult] = useState<string>('')

  const queryClient = useQueryClient()

  // 调试信息检查
  useEffect(() => {
    const token = localStorage.getItem('access_token')
    setDebugInfo({
      hasToken: !!token,
      tokenPreview: token ? token.substring(0, 20) + '...' : '无token',
      apiBaseUrl: '/api/v1'
    })
  }, [])

  // 测试API连接
  const testApiConnection = async () => {
    try {
      setTestResult('正在测试API连接...')
      const result = await jobApi.testConnection()
      setTestResult(`✅ API连接成功: ${result.message}`)
    } catch (error: any) {
      setTestResult(`❌ API连接失败: ${error.message}`)
    }
  }

  // 获取任务统计
  const { data: stats, isLoading: statsLoading } = useQuery(
    'job-stats',
    jobApi.getJobStats,
    {
      refetchInterval: 30000
    }
  )

  // 获取任务列表
  const { data: jobsData, isLoading: jobsLoading, refetch } = useQuery(
    ['jobs', searchText, statusFilter],
    () => jobApi.getJobs({
      search: searchText,
      status: statusFilter
    }),
    {
      refetchInterval: 15000
    }
  )

  // 任务操作mutation
  const createJobMutation = useMutation(jobApi.createJob, {
    onSuccess: () => {
      message.success('任务创建成功')
      setIsModalVisible(false)
      form.resetFields()
      refetch()
      queryClient.invalidateQueries('job-stats')
    },
    onError: (error: any) => {
      message.error(`创建失败: ${error.message}`)
    }
  })

  const updateJobMutation = useMutation(jobApi.updateJob, {
    onSuccess: () => {
      message.success('任务更新成功')
      setIsModalVisible(false)
      setEditingJob(null)
      form.resetFields()
      refetch()
      queryClient.invalidateQueries('job-stats')
    },
    onError: (error: any) => {
      message.error(`更新失败: ${error.message}`)
    }
  })

  const deleteJobMutation = useMutation(jobApi.deleteJob, {
    onSuccess: () => {
      message.success('任务删除成功')
      refetch()
      queryClient.invalidateQueries('job-stats')
    },
    onError: (error: any) => {
      message.error(`删除失败: ${error.message}`)
    }
  })

  const toggleJobMutation = useMutation(
    ({ jobId, isActive }: { jobId: string; isActive: boolean }) =>
      jobApi.toggleJobStatus(jobId, isActive),
    {
      onSuccess: (_, variables) => {
        message.success(`任务${variables.isActive ? '启用' : '禁用'}成功`)
        refetch()
        queryClient.invalidateQueries('job-stats')
      },
      onError: (error: any) => {
        message.error(`操作失败: ${error.message}`)
      }
    }
  )

  const executeJobMutation = useMutation(jobApi.executeJob, {
    onSuccess: (data) => {
      message.success(`任务执行成功，执行ID: ${data.execution_id}`)
      refetch()
    },
    onError: (error: any) => {
      message.error(`执行失败: ${error.message}`)
    }
  })

  // 事件处理
  const handleCreateJob = () => {
    setEditingJob(null)
    form.resetFields()
    setIsModalVisible(true)
  }

  const handleEditJob = (job: Job) => {
    setEditingJob(job)
    form.setFieldsValue({
      ...job,
      executor_params: job.executor_params || '{}'
    })
    setIsModalVisible(true)
  }

  const handleDeleteJob = (jobId: string) => {
    deleteJobMutation.mutate(jobId)
  }

  const handleToggleJob = (job: Job) => {
    toggleJobMutation.mutate({
      jobId: job.id,
      isActive: !job.is_active
    })
  }

  const handleExecuteJob = (jobId: string) => {
    executeJobMutation.mutate(jobId)
  }

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields()
      
      if (editingJob) {
        updateJobMutation.mutate({
          ...values,
          id: editingJob.id
        })
      } else {
        createJobMutation.mutate(values)
      }
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }

  const handleModalCancel = () => {
    setIsModalVisible(false)
    setEditingJob(null)
    form.resetFields()
  }

  // 表格列定义
  const columns: ColumnsType<Job> = [
    {
      title: '任务名称',
      dataIndex: 'job_name',
      key: 'job_name',
      width: 200,
      render: (text, record) => (
        <div>
          <div style={{ fontWeight: 500 }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            {record.description}
          </div>
        </div>
      )
    },
    {
      title: 'Cron表达式',
      dataIndex: 'cron_expression',
      key: 'cron_expression',
      width: 120,
      render: (text) => (
        <Tooltip title={jobUtils.getCronDescription(text)}>
          <code style={{ fontSize: '12px' }}>{text}</code>
        </Tooltip>
      )
    },
    {
      title: '处理器',
      dataIndex: 'executor_handler',
      key: 'executor_handler',
      width: 150,
      render: (text) => <Tag color="blue">{text}</Tag>
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 80,
      render: (isActive) => (
        <Tag color={isActive ? 'green' : 'red'}>
          {isActive ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '执行统计',
      key: 'execution_stats',
      width: 120,
      render: (_, record) => (
        <div style={{ fontSize: '12px' }}>
          <div>总计: {record.execution_count || 0}</div>
          <div style={{ color: '#52c41a' }}>成功: {record.success_count || 0}</div>
          <div style={{ color: '#ff4d4f' }}>失败: {record.failure_count || 0}</div>
        </div>
      )
    },
    {
      title: '成功率',
      key: 'success_rate',
      width: 80,
      render: (_, record) => {
        const total = record.execution_count || 0
        const success = record.success_count || 0
        const rate = total > 0 ? jobUtils.calculateSuccessRate(success, total) : '0%'
        const percent = parseInt(rate)
        const color = percent >= 90 ? '#52c41a' : percent >= 70 ? '#faad14' : '#ff4d4f'
        return <span style={{ color }}>{rate}</span>
      }
    },
    {
      title: '下次执行',
      dataIndex: 'next_execution_time',
      key: 'next_execution_time',
      width: 150,
      render: (time) => (
        time ? (
          <span style={{ fontSize: '12px' }}>
            {new Date(time).toLocaleString()}
          </span>
        ) : (
          <span style={{ color: '#999' }}>-</span>
        )
      )
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEditJob(record)}
            />
          </Tooltip>
          
          <Tooltip title={record.is_active ? '禁用' : '启用'}>
            <Button
              type="text"
              icon={record.is_active ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
              onClick={() => handleToggleJob(record)}
              loading={toggleJobMutation.isLoading}
            />
          </Tooltip>
          
          <Tooltip title="立即执行">
            <Button
              type="text"
              icon={<ClockCircleOutlined />}
              onClick={() => handleExecuteJob(record.id)}
              loading={executeJobMutation.isLoading}
              disabled={!record.is_active}
            />
          </Tooltip>
          
          <Tooltip title="执行历史">
            <Button
              type="text"
              icon={<HistoryOutlined />}
              onClick={() => message.info('执行历史功能开发中')}
            />
          </Tooltip>
          
          <Popconfirm
            title="确定要删除这个任务吗？"
            onConfirm={() => handleDeleteJob(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
                loading={deleteJobMutation.isLoading}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ]

  return (
    <div style={{ padding: '24px' }}>
      {/* 调试信息 */}
      <Alert
        message="调试信息"
        description={
          <div>
            <div>Token状态: {debugInfo.hasToken ? '✅ 已存在' : '❌ 未找到'}</div>
            <div>Token预览: {debugInfo.tokenPreview}</div>
            <div>API基础URL: {debugInfo.apiBaseUrl}</div>
            <div>当前时间: {new Date().toLocaleString()}</div>
            <div style={{ marginTop: '8px' }}>
              <Button 
                size="small" 
                onClick={testApiConnection}
                style={{ marginRight: '8px' }}
              >
                测试API连接
              </Button>
              {testResult && <span>{testResult}</span>}
            </div>
          </div>
        }
        type="info"
        showIcon
        style={{ marginBottom: '16px' }}
      />
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总任务数"
              value={stats?.total || 0}
              prefix={<ClockCircleOutlined />}
              loading={statsLoading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃任务"
              value={stats?.active || 0}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#3f8600' }}
              loading={statsLoading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="最近执行"
              value={stats?.recent_executions || 0}
              prefix={<PlayCircleOutlined />}
              loading={statsLoading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="成功率"
              value={stats?.success_rate || 0}
              suffix="%"
              prefix={<CheckCircleOutlined />}
              valueStyle={{ 
                color: (stats?.success_rate || 0) >= 90 ? '#3f8600' : '#cf1322' 
              }}
              loading={statsLoading}
            />
          </Card>
        </Col>
      </Row>

      {/* 任务列表 */}
      <Card
        title="定时任务管理"
        extra={
          <Space>
            <Input.Search
              placeholder="搜索任务名称"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 200 }}
            />
            <Select
              placeholder="状态筛选"
              value={statusFilter}
              onChange={setStatusFilter}
              style={{ width: 120 }}
              allowClear
            >
              <Option value="">全部</Option>
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreateJob}
            >
              新建任务
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={() => refetch()}
              loading={jobsLoading}
            >
              刷新
            </Button>
          </Space>
        }
      >
        <Table<Job>
          columns={columns}
          dataSource={jobsData?.jobs || []}
          rowKey="id"
          loading={jobsLoading}
          pagination={{
            total: jobsData?.total || 0,
            pageSize: 20,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新建/编辑任务Modal */}
      <Modal
        title={editingJob ? '编辑任务' : '新建任务'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={600}
        confirmLoading={createJobMutation.isLoading || updateJobMutation.isLoading}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="job_name"
            label="任务名称"
            rules={[{ required: true, message: '请输入任务名称' }]}
          >
            <Input placeholder="请输入任务名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="任务描述"
          >
            <TextArea
              placeholder="请输入任务描述"
              rows={3}
            />
          </Form.Item>

          <Form.Item
            name="cron_expression"
            label="Cron表达式"
            rules={[{ required: true, message: '请输入Cron表达式' }]}
            help="例如: 0 2 * * * (每日凌晨2点执行)"
          >
            <Input placeholder="0 2 * * *" />
          </Form.Item>

          <Form.Item
            name="executor_handler"
            label="处理器名称"
            rules={[{ required: true, message: '请选择处理器' }]}
          >
            <Select placeholder="请选择处理器">
              <Option value="sync_user_data">用户数据同步</Option>
              <Option value="cleanup_logs">日志清理</Option>
              <Option value="backup_database">数据库备份</Option>
              <Option value="send_notifications">发送通知</Option>
              <Option value="process_orders">订单处理</Option>
              <Option value="generate_reports">生成报表</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="executor_params"
            label="任务参数"
            help="JSON格式的参数配置"
          >
            <TextArea
              placeholder='{"key": "value"}'
              rows={4}
            />
          </Form.Item>

          <Form.Item
            name="is_active"
            label="启用状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default JobManagement